package part1;

import com.google.gson.Gson;
import lombok.Data;
import lombok.NonNull;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 使用网站http://www.rest7.com/提供的ip_to_city.php接口，
 * 编写程序查询ip地址（使用第一步获取到的ip地址）对应的城市名称。
 */
public class Q2 {

    /**
     * 获取指定 IP 的城市信息
     *
     * @param params 参数
     * @return City
     */
    public static City getCityByIP(@NonNull Map<String, String> params) {
        final Gson gson = new Gson();
        final AtomicReference<String> reqContent = new AtomicReference<>();
        final HttpClient client = HttpClient.newHttpClient();

        // TODO: POST ERROR
        // final HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://www.rest7.com/forward.php?api=ip_to_city.php"))
        //         .POST(HttpRequest.BodyPublishers.ofString(gson.toJson(params))).build();

        // GET
        final HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://api.rest7.com/v1/ip_to_city.php?ip=" + params.get("ip"))).build();
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::body).thenAccept(reqContent::set).join();
        System.out.println(reqContent);
        return gson.fromJson(reqContent.get(), City.class);
    }

    @Data
    public static class City {
        private String country;
        private String region;
        private String city;
        private String lat;
        private String lng;
        private String ip;
        private int success;
    }

}
